package net.rock.eshop.controller.manage;

import net.rock.eshop.entity.Category;
import net.rock.eshop.exception.InvalidRequestException;
import net.rock.eshop.exception.UnauthorizedOperationException;
import net.rock.eshop.service.CategoryService;
import net.rock.eshop.utils.AdminChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/manage/category")
public class CategoryManageController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    AdminChecker adminChecker;
    @PostMapping("/add")
    void addCategory(@CookieValue(value = "sessionID", defaultValue = "") String sessionId,
                     @RequestBody Map<String, String> body) {
        String name = body.get("name");
        if (name == null) {
            throw new InvalidRequestException();
        } else if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            categoryService.addCategory(name);
        }
    }

    @PostMapping("/del")
    void delCategory(@CookieValue(value = "sessionID", defaultValue = "") String sessionId,
                     @RequestBody Map<String, String> body) {
        String id = body.get("id");
        if (id == null) {
            throw new InvalidRequestException();
        } else if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            categoryService.delCategory(Integer.parseInt(id));
        }
    }

    @PostMapping("/edit")
    void editCategory(@CookieValue(value = "sessionID", defaultValue = "") String sessionId,
                      @RequestBody Category category) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            categoryService.editCategory(category);
        }
    }
}
